package com.sh.rpc.serializer;

import java.io.*;

/**
 * jdk 序列化
 * @author sh
 */
public class JdkSerializer implements Serializer{

    @Override
    public <T> byte[] serialize(T object) throws IOException {
        // 创建一个字节数组输出流，用于存放序列化后的数据
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 创建一个对象输出流，用于将对象写入到前面创建的字节数组输出流中
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        // 将传入的对象序列化并写入到对象输出流中
        objectOutputStream.writeObject(object);
        // 关闭对象输出流，释放资源
        objectOutputStream.close();
        // 将字节数组输出流中的数据转换成字节数组并返回
        return outputStream.toByteArray();
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> type) throws IOException {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);

        try {
            return (T) objectInputStream.readObject();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }finally {
            objectInputStream.close();
        }

    }
}
